<template>
  <div class="edit-cell" @click="onFieldClick">
    <el-tooltip
      v-if="!editMode && !showInput"
      :placement="toolTipPlacement"
      :open-delay="toolTipDelay"
      :content="toolTipContent"
    >
      <div tabindex="0" @keyup.enter="onFieldClick">
        <slot name="content"></slot>
      </div>
    </el-tooltip>
    <component
      :is="editableComponent"
      v-if="editMode || showInput"
      ref="input"
      v-bind="$attrs"
      v-model="model"
      clearable
      @focus="onFieldClick"
      @keyup.enter.native="onInputExit"
      v-on="listeners"
    >
      <slot name="edit-component-slot"></slot>
    </component>
  </div>
</template>

<script>
const { decimal } = require("@/util");
export default {
  name: "EditableCell",
  inheritAttrs: false,
  props: {
    value: {
      type: [String, Number],
      default: "",
    },
    type: {
      type: [String],
      default: "",
    },
    toolTipContent: {
      type: String,
      default: "点击编辑",
    },
    toolTipDelay: {
      type: Number,
      default: 500,
    },
    toolTipPlacement: {
      type: String,
      default: "top-start",
    },
    showInput: {
      type: Boolean,
      default: true,
    },
    editableComponent: {
      type: String,
      default: "el-input",
    },
    closeEvent: {
      type: String,
      default: "blur",
    },
  },
  data() {
    return {
      editMode: false,
      tempValue: this.value,
    };
  },
  computed: {
    model: {
      get() {
        return this.tempValue;
      },
      set(val) {
        this.$emit("input", val);
      },
    },
    listeners() {
      return {
        [this.closeEvent]: this.onInputExit,
        ...this.$listeners,
      };
    },
  },
  watch: {
    value(val) {
      if (this.type == "number") {
        this.tempValue = decimal(String(val), 2);
        // this.tempValue = String(val).match(/\d+(\.\d{0,2})?/) ? String(val).match(/\d+(\.\d{0,2})?/)[0] : "";
      } else {
        this.tempValue = val;
      }
    },
  },
  methods: {
    onFieldClick() {
      this.editMode = true;
      this.$nextTick(() => {
        const inputRef = this.$refs.input;
        if (inputRef) {
          inputRef.focus();
        }
      });
    },
    onInputExit() {
      this.editMode = false;
    },
    onInputChange(val) {
      this.$emit("input", val);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 160px;
}

.el-input--small .el-input {
  width: 160px;
}
</style>
